package com.shengdong.water.code.network.interceptor

import android.annotation.SuppressLint
import android.os.Handler
import android.os.Looper
import android.util.Log
import androidx.datastore.preferences.core.edit
import com.hjq.toast.Toaster
import com.shengdong.water.WaterApp
import com.shengdong.water.code.config.RouterConfig
import com.shengdong.water.code.config.UserConfig
import com.shengdong.water.code.router.RouterManager
import com.shengdong.water.code.utils.DataStoreUtil
import com.shengdong.water.code.utils.DataStoreUtil.dataStore
import kotlinx.coroutines.runBlocking
import okhttp3.Interceptor
import okhttp3.Response
import java.util.concurrent.atomic.AtomicBoolean
import javax.inject.Inject

class AuthInterceptor @Inject constructor(
) : Interceptor {

    // 防止多个401同时触发登录页面
    private val unauthorized = AtomicBoolean(false)

    @SuppressLint("SuspiciousIndentation")
    override fun intercept(chain: Interceptor.Chain): Response {
        val request = chain.request()
        //获取token
        val token = getToken()
        Log.e("token", token)
        if(UserConfig.token.isEmpty()) {
            //添加认证头
            val authHeader = request.newBuilder().header("Authorization", token).build()
                return chain.proceed(authHeader)
        }
        val tokenHeader = request.newBuilder().header("sdzn-framework-auth", token).build()

        val response = chain.proceed(tokenHeader)

        // 处理401错误
        if (response.code == 401 && !unauthorized.getAndSet(true)) {
            // 在主线程中处理UI相关操作
            Handler(Looper.getMainLooper()).post {
                // 清除用户信息
                UserConfig.clearSync()
                Toaster.show("登录过期,请重新登录")
                // 跳转到登录页面
                RouterManager.navigateToLogin(RouterConfig.LOGIN_PATH)

                // 重置标志
                unauthorized.set(false)
            }
        }
        return response
    }

    private fun getToken(): String {
        if(UserConfig.token.isEmpty()) return "Basic c2FiZXI6c2FiZXJfc2VjcmV0"
        UserConfig.token.let {
            return "Bearer $it"
        }
    }

}